import axios from 'axios'
import config from '@config'
class Http {  

  constructor() {
    this.interceptors();
  }

  async get(url, params = {}, header = {}) {
    return await axios.get(config.check() + url, {
      params: params,
      headers: header
    })
  }


  async post(url, params = {}, header = {}) {
    return await axios.post(config.check() + url, params, {
      params: params,
      headers: header
    })
  }
  // async post(url, params = {},header={}) {
  //   return await axios.post(config.check()+url, params,{
  //     headers: Object.assign(
  //       header,
  //         {token: localStorage.getItem("token")}
  //     ),
  //   })
  // }

  interceptors() {
    axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      return config;
    }, function (error) {
    });

    axios.interceptors.response.use(async function (response) {
        //响应数据进行处理
        if (response.data.hasOwnProperty("resultFlag")) {
          if (response.data.resultFlag == 0) {
            return response.data;
          } else {
            await alert(response.data.errorMsg);
            throw new Error(response.data.errorMsg);
          }
        } else {
          if (response.status == 200 || response.status == 403) {
            return response
          }
        }

      },
      function (error) {
        // 对响应错误做点什么
        // alert("请求错误或登陆失效")
        // location.href = "#/login"
        // localStorage.clear()
        let a = error
        let b = JSON.parse(JSON.stringify(a))
        console.log(b);
        if(b.message == "Network Error"){
          console.log(33);
          alert("插件未安装")
        }else if(b.message == 'Request failed with status code 501'){
          alert("登陆失效请重新登录")
          location.href = "#/login"
          localStorage.clear()
        }
        // else if(b.message == 'Request failed with status code 404'){
        //   alert("登陆失效请重新登录")
        //   location.href = "#/login"
        //   localStorage.clear()
        // }
        // console.log(Promise.resolve(error.response));
        // console.log("Promise", error,Promise.reject(error));
        return Promise.reject(error);
      }
      );

  }

  SetBaseUrl() {
    axios.defaults.baseURL = config.check();
  }
}

export default new Http()